package com.example.bigwork.controller;

import com.example.bigwork.dto.request.OrderCreateRequest;
import com.example.bigwork.dto.response.OrderResponse;
import com.example.bigwork.enums.OrderStatus;
import com.example.bigwork.service.OrderService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/order")
public class OrderController {

    private final OrderService orderService;

    @Autowired
    public OrderController(OrderService orderService) {
        this.orderService = orderService;
    }

    @PostMapping
    public ResponseEntity<OrderResponse> createOrder(@Valid @RequestBody OrderCreateRequest createRequest) {
        // In a real app, userId in createRequest might be ignored and taken from authenticated principal
        OrderResponse orderResponse = orderService.createOrder(createRequest);
        return new ResponseEntity<>(orderResponse, HttpStatus.CREATED);
    }

    @GetMapping("/{orderNumber}")
    public ResponseEntity<OrderResponse> getOrderByOrderNumber(@PathVariable String orderNumber) {
        OrderResponse orderResponse = orderService.getOrderByOrderNumber(orderNumber);
        return ResponseEntity.ok(orderResponse);
    }

    @GetMapping("/id/{orderId}") // Added endpoint to get by numeric ID
    public ResponseEntity<OrderResponse> getOrderById(@PathVariable Long orderId) {
        OrderResponse orderResponse = orderService.getOrderById(orderId);
        return ResponseEntity.ok(orderResponse);
    }

    @GetMapping("/user/{userId}")
    public ResponseEntity<List<OrderResponse>> getOrdersByUserId(@PathVariable Long userId) {
        // Ensure the authenticated user is requesting their own orders or is an admin
        List<OrderResponse> orders = orderService.getOrdersByUserId(userId);
        return ResponseEntity.ok(orders);
    }

    @PatchMapping("/{orderNumber}/status") // PATCH is suitable for partial updates like status change
    public ResponseEntity<OrderResponse> updateOrderStatus(
            @PathVariable String orderNumber,
            @RequestBody Map<String, String> statusUpdate) { // Expecting {"status": "PAID"}
        String newStatusStr = statusUpdate.get("status");
        if (newStatusStr == null) {
            return ResponseEntity.badRequest().build(); // Or throw custom exception
        }
        try {
            OrderStatus newStatus = OrderStatus.valueOf(newStatusStr.toUpperCase());
            OrderResponse orderResponse = orderService.updateOrderStatus(orderNumber, newStatus);
            return ResponseEntity.ok(orderResponse);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(null); // Or return custom error response DTO
        }
    }
}

